<?php

namespace app\speedDating\services\common;

use app\speedDating\exception\ServiceRuntimeException;
use app\speedDating\exception\SimpleValidateException;
use app\speedDating\interfaces\ServiceCode;
use app\speedDating\interfaces\ServiceStatus;
use app\speedDating\interfaces\ServiceMsgText;
use app\speedDating\model\SddFinanceAccountLog;
use app\speedDating\model\SddFinanceAccount;
use think\facade\Db;

class FinanceUtilsService
{

    /**
     * 校验账本状态,并返回账本信息
     * @param $id
     * @return \app\speedDating\model\traits\SimpleModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function accountCheck($id)
    {
        $account = SddFinanceAccount::getSimpleMainByID($id, true);
        if (empty($account)) {
            throw new ServiceRuntimeException(ServiceMsgText::ERR_ACCOUNT_NOT_EXIST,ServiceCode::ERR_ACCOUNT_NOT_EXIST);
        }
        if ($account->is_banned == ServiceStatus::ACCOUNT_STATUS_FREEZE) {
            throw new SimpleValidateException(ServiceMsgText::ERR_ACCOUNT_BANNED,ServiceCode::ERR_ACCOUNT_BANNED);
        }

        return $account;
    }

    /**
     * 创建记录,且根据记录操作账本
     * @param $id
     * @param $balance
     * @param $remark
     * @param $order
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function financeLogGenerate($id, $balance, $remark = null, $order = null)
    {
        $account = self::accountCheck($id);
        $data['account_id'] = $id;
        $data['account_type'] = $account['account_type'];
        $data['balance'] = $balance;
        $data['after_balance'] = $account['balance'] + $balance;
        $data['remark'] = $remark;
        $data['order_id'] = $order->id ?? 0;

        return Db::transaction(function () use ($data, $account) {
            $account->balance += $data['balance'];
            if ($account->balance < 0) {
                $accountTypeText = array_column(ServiceStatus::ACCOUNT_TYPE, 'label', 'state')[$account['account_type']];
                throw new ServiceRuntimeException(sprintf(ServiceMsgText::ERR_ACCOUNT_BALANCE_LOSE_DETAIL, $accountTypeText),ServiceCode::ERR_ACCOUNT_BALANCE_LOSE_DETAIL);
            }
            $account->save();
            //操作记录
            $insData = array_filter($data);
            return SddFinanceAccountLog::toInsert($insData);
        });
    }
}